<template>
    <van-popup v-model:show="modelValue" position="bottom" @close="confirmOn" :close-on-click-overlay="false">
        <van-picker v-model="data.selectedValues"ref="picker" title="请选择时间" :columns="data.columns" :defaultIndex="data.defaultIndex"
            @change="onChange" @cancel="cancelOn" @confirm="onConfirm" :columns-field-names="customFieldName" />
    </van-popup>
</template>

<script setup>
import { reactive, watch, ref } from 'vue';

const modelValue = defineModel('modelValue');
const timeValue = defineModel('timeValue');

const customFieldName = {
    text: 'text',
    value: 'value'
};

const data = reactive({
    columns: [], // 所有时间列
    selectedValues: [], // 控件选择的时间值
    defaultIndex: [0, 0, 0, 0, 0, 0] // 默认滚动位置
});

const props = defineProps({
    defaultValue: {
        type: String,
        default: ""
    }
});

watch(
    () => modelValue.value,
    val => {
        if (val) {
            data.columns = [];
            getcolumns();
        }
    },
    {
        immediate: true
    }
);

function onChange(picker, values, index) {
    if (index === 0 || index === 1) {
        const year = parseInt(values[0].value);
        const month = parseInt(values[1].value);
        updateDays(year, month);
    }
}

function getcolumns() {
    let dateVaules;
    if (props.defaultValue) {
        let strtime = props.defaultValue;
        let date = new Date(strtime.replace(/-/g, "/"));
        dateVaules = date;
    } else if (timeValue.value) {
        let strtime = timeValue.value;
        let date = new Date(strtime.replace(/-/g, "/"));
        dateVaules = date;
    } else {
        dateVaules = new Date();
    }

    let Y = dateVaules.getFullYear();
    let M = dateVaules.getMonth();
    let D = dateVaules.getDate();
    let h = dateVaules.getHours();
    let m = dateVaules.getMinutes();
    let s = dateVaules.getSeconds();

    // 生成年份选项，扩大范围到更早的年份
    let year = [];
    let Currentday = new Date().getFullYear();
    for (let i = Currentday - 50; i < Currentday + 10; i++) {
        year.push({ text: i.toString() + '年', value: i });
    }

    // 生成月份选项
    let month = [];
    for (let i = 1; i <= 12; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        month.push({ text: value + '月', value });
    }

    // 生成日期选项
    let days = getCountDays(Y, M + 1);
    let day = [];
    for (let i = 1; i <= days; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        day.push({ text: value + '日', value });
    }

    // 生成小时选项
    let hour = [];
    for (let i = 0; i < 24; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        hour.push({ text: value + '时', value });
    }

    // 生成分钟选项
    let minute = [];
    for (let i = 0; i < 60; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        minute.push({ text: value + '分', value });
    }

    // 生成秒钟选项
    let second = [];
    for (let i = 0; i < 60; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        second.push({ text: value + '秒', value });
    }

    // 设置所有列
    data.columns = [year, month, day, hour, minute, second];

    // 设置默认值和滚动位置
    const defaultM = (M + 1) < 10 ? `0${M + 1}` : (M + 1).toString();
    const defaultD = D < 10 ? `0${D}` : D.toString();
    const defaultH = h < 10 ? `0${h}` : h.toString();
    const defaultMin = m < 10 ? `0${m}` : m.toString();
    const defaultS = s < 10 ? `0${s}` : s.toString();

    // 计算默认选中值的索引
    data.selectedValues = [Y, defaultM, defaultD, defaultH, defaultMin, defaultS];
    data.defaultIndex = [
        year.findIndex(item => item.value === Y),
        month.findIndex(item => item.value === defaultM),
        day.findIndex(item => item.value === defaultD),
        hour.findIndex(item => item.value === defaultH),
        minute.findIndex(item => item.value === defaultMin),
        second.findIndex(item => item.value === defaultS)
    ];

    if (timeValue.value) {
        let strtime = timeValue.value;
        let date = new Date(strtime.replace(/-/g, "/"));
        let Y = date.getFullYear();
        let M = date.getMonth() + 1;
        let D = date.getDate();
        let H = date.getHours();
        let Min = date.getMinutes();
        let S = date.getSeconds();
        
        data.selectedValues = [
            Y, 
            M < 10 ? `0${M}` : M.toString(), 
            D < 10 ? `0${D}` : D.toString(), 
            H < 10 ? `0${H}` : H.toString(), 
            Min < 10 ? `0${Min}` : Min.toString(), 
            S < 10 ? `0${S}` : S.toString()
        ];
    }
    
}

function getCountDays(year, month) {
    return new Date(year, month, 0).getDate();
}

function updateDays(year, month) {
    const days = getCountDays(year, month);
    let dayColumn = [];
    for (let i = 1; i <= days; i++) {
        const value = i < 10 ? `0${i}` : i.toString();
        dayColumn.push({ text: value + '日', value });
    }
    data.columns[2] = dayColumn;
}

function confirmOn() {
    modelValue.value = false;
}

function cancelOn() {
    confirmOn();
}

function onConfirm({ selectedValues }) {
    const formattedTime =
        selectedValues[0] +
        "-" +
        selectedValues[1] +
        "-" +
        selectedValues[2] +
        " " +
        selectedValues[3] +
        ":" +
        selectedValues[4] +
        ":" +
        selectedValues[5];

    timeValue.value = formattedTime;
    confirmOn();
}
</script>

<style lang="less" scoped>
.van-picker {
    width: 100%;

    :deep(.van-picker-column) {
        flex: none;
        min-width: 50px;

        &:nth-child(1) {
            flex: 0 0 80px; // 年份列宽度
        }

        &:nth-child(2),
        &:nth-child(3) {
            flex: 0 0 60px; // 月份和日期列宽度
        }

        &:nth-child(4),
        &:nth-child(5),
        &:nth-child(6) {
            flex: 0 0 55px; // 时分秒列宽度
        }
    }

    /deep/.van-picker__columns {
        justify-content: center;
    }
}

.van-popup--bottom {
    width: 33.4% !important;
}
</style>